package com.anxinr.config;

import com.anxinr.filter.ProjectFilter;
import com.anxinr.interceptor.StudyInterceptor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {

    @Autowired
    private StudyInterceptor studyInterceptor ;
    /**
     * 设置拦截器拦截地址和放行地址
     * */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(studyInterceptor)
                .addPathPatterns("/**")
                .excludePathPatterns("/user/login")
                .excludePathPatterns("/user/register")
        ;
    }
    //跨域访问
    @Bean
    public WebMvcConfigurer corsConfigurer() {
        return new WebMvcConfigurer() {
            @Override
            //重写父类提供的跨域请求处理的接口
            public void addCorsMappings(CorsRegistry registry) {
                //添加映射路径
                registry.addMapping("/**")
                        //放行哪些原始域
                        .allowedOrigins("*")
                        //是否发送Cookie信息
                        .allowCredentials(true)
                        //放行哪些原始域(请求方式)
                        .allowedMethods("GET", "POST", "PUT", "DELETE","OPTIONS")
                        //放行哪些原始域(头部信息)
                        .allowedHeaders("*")
                        //暴露哪些头部信息（因为跨域访问默认不能获取全部头部信息）
                        .exposedHeaders("Header1", "Header2");
            }
        };
    }


    /**
     * desc 添加request请求体过滤器
     * date 2022/9/6 9:46
     * @author fmk
     * @return {@link FilterRegistrationBean}
     */
    @Bean
    public FilterRegistrationBean<ProjectFilter> xssFilterRegistration() {
        FilterRegistrationBean<ProjectFilter> registration = new FilterRegistrationBean<>();
        registration.setFilter(new ProjectFilter());
        registration.addUrlPatterns("/**");
        registration.setName("requestBodyFilter");
        registration.setOrder(0);
        return registration;
    }
}
